package com.sky.task;

import com.alibaba.fastjson.JSON;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangyu
 * @data 2023/4/26 15:04
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 模拟用户支付成功后提醒商家来单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void payAnOrder(){
        List<Orders> payAnOrders = orderMapper.getStatus();
        if(payAnOrders!=null&&payAnOrders.size()>0){
            for (Orders payAnOrder : payAnOrders) {
                Map map=new HashMap();
                map.put("type",1);
                map.put("orderId",payAnOrder.getId());
                map.put("content","订单号:"+payAnOrder.getNumber());
                webSocketServer.sendToAllClient(JSON.toJSONString(map));
            }
        }
    }
    /**
     * 每分钟检查一次是否有支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder() {
        log.info("检查超时订单中......: {}", new Date());
        List<Orders> orders = orderMapper.checkOrderStatus(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        //如果orders不为空
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                log.error("超时订单号: {}", order.getNumber());
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单支付超时");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    /**
     * 每天凌晨一点检查昨天是否还有派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("开始检查昨天是否还有派送中的订单: {}", new Date());
        List<Orders> orders = orderMapper.checkOrderStatus(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        //如果orders不为空
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                log.info("自动将订单号为: {}" + order.getNumber() + "设置为已完成");
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
